package com.ysq.www.api.work.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ysq.www.api.user.entity.User;
import com.ysq.www.api.user.mapper.UserMapper;
import com.ysq.www.api.work.entity.Approve;
import com.ysq.www.api.work.entity.Conference;
import com.ysq.www.api.work.entity.CopyTo;
import com.ysq.www.api.work.mapper.ApproveMapper;
import com.ysq.www.api.work.mapper.ConferenceMapper;
import com.ysq.www.api.work.mapper.CopyToMapper;
import com.ysq.www.api.work.service.IConferenceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysq.www.common.result.ResultMsg;
import com.ysq.www.common.utils.Comm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 会议表 服务实现类
 * </p>
 *
 * @author dql
 * @since 2020-08-11
 */
@Service
public class ConferenceServiceImpl extends ServiceImpl<ConferenceMapper, Conference> implements IConferenceService {

    @Autowired
    private ConferenceMapper conferenceMapper;

    @Autowired
    private ApproveMapper approveMapper;

    @Autowired
    private CopyToMapper copyToMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 提交会议
     * @param cf 会议对象
     * @return ResultMsg
     */
    @Override
    @Transactional
    public ResultMsg addConference(Conference cf) {
        cf.setCheckStatus(0);
        cf.setCreateTime(Comm.getNow());
        cf.setStatus(0);
        boolean save = this.save(cf);
        if (save){//创建审批记录
            Approve app = new Approve();
            app.setType(4);//类型会议
            app.setContentId(cf.getId());
            app.setCheckId(cf.getApproverId());
            app.setSupperId(0);
            app.setLowerId(0);
            app.setCheckTime(Comm.getNow());
            app.setCheckStatus(0);
            app.setCreateTime(Comm.getNow());
            app.setStatus(0);
            approveMapper.insert(app);

            //创建抄送记录
            String copyIds = cf.getCopyId();
            if (!StringUtils.isEmpty(copyIds)){
                List<CopyTo> cList = new ArrayList<>();
                String[] copyId = copyIds.split(";");
                for (String c : copyId) {
                    CopyTo ct = new CopyTo();
                    ct.setType(3);//会议
                    ct.setContentId(cf.getId());//内容id
                    ct.setUserId(Integer.parseInt(c));//抄送至用户的id
                    ct.setCreateTime(Comm.getNow());//创建时间
                    ct.setStatus(0);
                    cList.add(ct);
                }
                if (cList.size() > 0){
                    //copyToMapper.insertList(cList);
                    copyToMapper.insertListByNote(cList);
                }
            }
            return ResultMsg.INSERT_SUCCESS.setNewMsg("提交成功");
        }else return ResultMsg.UPDATE_ERROR.setNewMsg("提交失败,内部错误");
    }

    /**
     * 分页查询我发起的会议
     * @param userId 发起人id
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param time 日期
     * @return IPage
     */
    @Override
    public IPage<Conference> selectSponsorByPage(Integer userId, Integer pageNumber, Integer pageSize, String time) {
        QueryWrapper<Conference> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).eq("user_id",userId);
        if (!StringUtils.isEmpty(time)){
            String startTime = time + " 00:00:00";
            String endTime = time + " 23:59:59";
            wrapper.between("create_time",startTime,endTime);
        }
        wrapper.orderByDesc("create_time");
        Page<Conference> page = new Page<>(pageNumber,pageSize);
        return conferenceMapper.selectPage(page,wrapper);
    }

    /**
     * 分页查询待处理/已处理会议
     * @param userId 审批人id
     * @param type 类型：0未处理，1已处理
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param time 日期
     * @return IPage
     */
    @Override
    public IPage<Conference> selectPendingByPage(Integer userId, Integer type, Integer pageNumber, Integer pageSize, String time) {
        QueryWrapper<Conference> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).eq("approver_id",userId);
        if (type == 0) wrapper.eq("check_status",0);
        else if (type == 1){
            wrapper.ne("check_status",0).ne("check_status",3);
            if (!StringUtils.isEmpty(time)){
                String startTime = time + " 00:00:00";
                String endTime = time + " 23:59:59";
                wrapper.between("create_time",startTime,endTime);
            }
        }
        wrapper.orderByDesc("create_time");
        Page<Conference> page = new Page<>(pageNumber,pageSize);
        return conferenceMapper.selectPage(page,wrapper);
    }

    /**
     * 查询我发起的会议详情
     * @param cId 会议id
     * @return Conference
     */
    @Override
    public Conference selectDetailById(Integer cId) {
        Conference cf = conferenceMapper.selectDetailById(cId);
        return getAttendAndCopy(cf);
    }

    /**
     * 分页查询抄送至我的会议
     * @param userId 用户id
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param time 日期
     * @return IPage
     */
    @Override
    public IPage<Conference> selectCopyToByPage(Integer userId, Integer pageNumber, Integer pageSize, String time) {
        QueryWrapper<CopyTo> cWrapper = new QueryWrapper<>();
        cWrapper.eq("status",0).eq("user_id",userId).eq("type",3);
        List<CopyTo> cList = copyToMapper.selectList(cWrapper);
        if (cList.isEmpty()) return null;
        List<Integer> idList = new ArrayList<>();
        for (CopyTo c : cList) {
            idList.add(c.getContentId());
        }
        QueryWrapper<Conference> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).ne("check_status",3).in("id",idList);
        if (!StringUtils.isEmpty(time)){
            String startTime = time + " 00:00:00";
            String endTime = time + " 23:59:59";
            wrapper.between("create_time",startTime,endTime);
        }
        wrapper.orderByDesc("create_time");
        Page<Conference> page = new Page<>(pageNumber,pageSize);
        return conferenceMapper.selectPage(page,wrapper);
    }

    /**
     * 审批处理提交的会议
     * @param cId 会议id
     * @param result 处理结果：1通过，2驳回
     * @return ResultMsg
     */
    @Override
    public ResultMsg checkConferenceById(Integer cId, Integer result) {
        Conference cf = conferenceMapper.selectById(cId);
        if (cf.getCheckStatus() != 0) return ResultMsg.UPDATE_ERROR.setNewMsg("处理失败，该会议已处理或已撤销!");
        cf.setCheckStatus(result);
        cf.setUpdateTime(Comm.getNow());
        this.updateById(cf);
        UpdateWrapper<Approve> wrapper = new UpdateWrapper<>();
        wrapper.set("check_time",Comm.getNow()).set("check_status",result).set("update_time",Comm.getNow()).
                eq("type",4).eq("content_id",cId);
        approveMapper.update(null,wrapper);
        return ResultMsg.SUCCESS.setNewMsg("处理成功");
    }

    /**
     * 撤销会议
     * @param cId 会议id
     * @return ResultMsg
     */
    @Override
    public ResultMsg repealConferenceById(Integer cId) {
        Conference cf = this.getById(cId);
        if (cf.getCheckStatus() != 0) return ResultMsg.UPDATE_ERROR.setNewMsg("撤销失败,已处理不能撤销");
        cf.setCheckStatus(3);
        cf.setUpdateTime(Comm.getNow());
        this.updateById(cf);
        UpdateWrapper<Approve> wrapper = new UpdateWrapper<>();
        wrapper.set("check_time",Comm.getNow()).set("check_status",3).set("update_time",Comm.getNow()).
                eq("type",4).eq("content_id",cId);
        approveMapper.update(null,wrapper);
        return ResultMsg.SUCCESS.setNewMsg("撤销成功");
    }


    /**
     * 公用方法
     * 获取参会人集合、抄送人集合
     */
    public Conference getAttendAndCopy(Conference cf){
        //获取参加会议人员集合
        String[] arrays = cf.getAttendId().split(";");
        List<Integer> idList = new ArrayList<>();
        for (String s : arrays) {
            idList.add(Integer.parseInt(s));
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).in("id",idList);
        List<User> userList = userMapper.selectList(wrapper);
        cf.setAttendList(userList);
        String copyIds = cf.getCopyId();//抄送人id字符串
        if (StringUtils.isEmpty(copyIds)) return cf;
        String[] cArray = copyIds.split(";");
        List<Integer> cIdList = new ArrayList<>();
        for (String c : cArray) {
            cIdList.add(Integer.parseInt(c));
        }
        QueryWrapper<User> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("status",0).in("id",cIdList);
        List<User> copyList = userMapper.selectList(wrapper1);
        cf.setCopyList(copyList);
        return cf;
    }
}
